package com.airsaid.pickerviewlibrary;

import android.content.Context;
import android.content.res.AssetManager;
import android.text.TextUtils;
import android.util.Log;
import com.airsaid.pickerviewlibrary.bean.Area;
import com.airsaid.pickerviewlibrary.bean.City;
import com.airsaid.pickerviewlibrary.bean.Province;
import com.airsaid.pickerviewlibrary.bean.Result;
import com.airsaid.pickerviewlibrary.listener.OnSelectListener;
import com.google.gson.Gson;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zbsdata on 2017/2/27.
 */

public class PickerCityUtils extends OptionsPickerView {

    private Context mContext;
    // 省数据集合
    private ArrayList<String> mListProvince = new ArrayList<String>();
    // 市数据集合
    private ArrayList<ArrayList<String>> mListCity = new ArrayList<ArrayList<String>>();
    // 区数据集合
    private ArrayList<ArrayList<ArrayList<String>>> mListArea = new ArrayList<ArrayList<ArrayList<String>>>();

    //    private String  fileName = "json.txt" ;
    private static String fileName = "area.json";

    //省索引
    private int option1 = 0;
    //市索引
    private int option2 = 0;
    //区索引
    private int option3 = 0;


    public PickerCityUtils(Context context,String ... filePath) {
        super(context);
        this.mContext = context;
        if (filePath!=null && filePath.length>0){
            //方式一 ：使用文件的形式获取
            File file = new File(filePath[0]);
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
                initJsonData(bufferedInputStream);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }else {
            //方式二 ：本地内置文件获取
            try {
                AssetManager assets = mContext.getAssets();
                InputStream is = assets.open(fileName);
                initJsonData(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        initCitySelect();
    }





    /**
     * @param p
     * @param c
     * @param a
     */
    public void setCheckPosition(String p, String c, String a, OnSelectListener onSelectListener) {
        option1 = option2 = option3 = 0;
        try {
            if (!TextUtils.isEmpty(p)) {
                for (int i = 0; i < mListProvince.size(); i++) {
                    String pBean = mListProvince.get(i);
                    if (p.contains(pBean)) {
                        option1 = i;
                        break;
                    }
                }


                if (!TextUtils.isEmpty(c)) {
                    ArrayList<String> cList = mListCity.get(option1);
                    if (cList != null && cList.size() > 0) {
                        for (int j = 0; j < cList.size(); j++) {
                            String cBean = cList.get(j);
                            if (c.contains(cBean)) {
                                option2 = j;
                                break;
                            }
                        }
                    }
                }


                if (!TextUtils.isEmpty(a)) {
                    ArrayList<String> aList = mListArea.get(option1).get(option2);
                    if (aList != null && aList.size() > 0) {
                        for (int k = 0; k < aList.size(); k++) {
                            String aBean = aList.get(k);
                            if (a.contains(aBean)) {
                                option3 = k;
                                break;
                            }
                        }
                    }
                }
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

        if (onSelectListener != null) {
            onSelectListener.onCitySelect(option1, option2, option3);
        }
        Log.v("[setCheckPosition]->", "option1 = " + option1 + " , option2 = " + option2 + " , option3 = " + option3);
    }


    private void initCitySelect() {
        setTitle("选择城市");
        setPicker(mListProvince, mListCity, mListArea, true);
        setCyclic(false, false, false);
        setSelectOptions(option1, option2, option3);
        setOnOptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int option1, int option2, int option3) {
                PickerCityUtils.this.option1 = option1;
                PickerCityUtils.this.option2 = option2;
                PickerCityUtils.this.option3 = option3;
                try {
                    if (mOnCitySelectListener != null) {
                        String Province = "";
                        String City = "";
                        String Area = "";

                        //省
                        if (mListProvince.size() > 0) {
                            Province = mListProvince.get(option1);
                        }

                        //市
                        if (mListCity.size() > 0 && mListCity.get(option1).size() > 0) {
                            City = mListCity.get(option1).get(option2);
                        }

                        //区
                        if (mListArea.size() > 0
                                && mListArea.get(option1).size() > 0
                                && mListArea.get(option1).get(option2).size() > 0) {
                            Area = mListArea.get(option1).get(option2).get(option3);
                        }

                        mOnCitySelectListener.onCitySelect(Province, City, Area);
                        mOnCitySelectListener.onCitySelect(Province.concat(City).concat(Area), option1, option2, option3);
                    }
                } catch (IndexOutOfBoundsException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * 从assets文件夹中读取省市区的json文件，然后转化为json对象
     * <p>
     * <p>
     * fileName 需要获取文件的名字
     */
    private void initJsonData(InputStream is ) {
        try {
            byte[] buf = new byte[is.available()];
            is.read(buf);
            String json = new String(buf, "UTF-8");
            /**/
            Result r = new Gson().fromJson(json, Result.class);
            Log.v("=====mListProvince=", String.valueOf(json));
            List<Province> list = r.getResult();

            for (Province p : list) {
                /*省*/
                mListProvince.add(p.getName());
                Log.v("=====省=", p.getName());

                /*市*/
                List<City> city = p.getSubdb();
                mListCity.add(getStringLsit(city));

                /*区*/
                ArrayList<ArrayList<String>> A = new ArrayList<ArrayList<String>>();
                for (City c : city) {
                    Log.v("=========省市=", c.getName());
                    List<Area> mA = c.getSubdb();
                    A.add(getStringLsit1(mA));
                    for (Area s : mA) {
                        Log.v("=========省市区=", s.getName());
                    }
                }
                mListArea.add(A);
                Log.v("=========省市区=", new Gson().toJson(mListArea));
            }
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param city
     * @return
     */
    public ArrayList<String> getStringLsit(List<City> city) {
        ArrayList<String> cList = new ArrayList<String>();
        for (City c : city) {
            cList.add(c.getName());
        }
        return cList;
    }


    /**
     * @param area
     * @return
     */
    public ArrayList<String> getStringLsit1(List<Area> area) {
        ArrayList<String> cList = new ArrayList<String>();
        for (Area c : area) {
            cList.add(c.getName());
        }
        return cList;
    }


    public OnCitySelectListener mOnCitySelectListener;

    public interface OnCitySelectListener {
        void onCitySelect(String str, int option1, int option2, int option3);

        void onCitySelect(String p, String city, String area);
    }


    public void setOnCitySelectListener(OnCitySelectListener listener) {
        this.mOnCitySelectListener = listener;
    }


    /**
     * 获取地址列表
     *
     * @param context
     * @return
     */
    public static List<Province> getAddressList(Context context) {
        AssetManager assets = context.getAssets();
        InputStream is = null;
        try {
            is = assets.open(fileName);
            byte[] buf = new byte[is.available()];
            is.read(buf);
            String json = new String(buf, "UTF-8");
            Result r = new Gson().fromJson(json, Result.class);
            Log.v("=====mListProvince=", "json = " + json);
            List<Province> list = r.getResult();
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
